package org.me.rmi.Skeleton;

import org.me.rmi.Interface.IPerson;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketException;

/**
 * Created by wangyg on 2016/11/1.
 */
public class PersonSkeleton extends Thread {

	private IPerson person;
	private Socket socket;

	public PersonSkeleton(IPerson person, Socket socket) {
		this.person = person;
		this.socket = socket;
	}

	public void run() {
		try {
			while (true) {
				// get stub's request
				InputStream inputStream = socket.getInputStream();

				ObjectInputStream inStream = new ObjectInputStream(inputStream);

				String method = (String) inStream.readObject();
				// check method name
				if (method.equals("age")) {
					// execute object server's business method
					int age = person.getAge();
					ObjectOutputStream outStream =
							new ObjectOutputStream(socket.getOutputStream());
					// return result to stub
					outStream.writeInt(age);
					outStream.flush();
				}
				if (method.equals("name")) {
					// execute object server's business method
					String name = person.getName();
					ObjectOutputStream outStream =
							new ObjectOutputStream(socket.getOutputStream());
					// return result to stub
					outStream.writeObject(name);
					outStream.flush();
				}
			}

//		} catch (SocketException s) {
//			try {
//				socket.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
		} catch (Throwable t) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
//			t.printStackTrace();
//			System.exit(0);
		}
	}

}

